package bll

import (
	"context"
	"fmt"
	"go.uber.org/zap"
	"maya-service/bll/weixin"
	log "maya-service/collector/logger"
	"maya-service/collector/trace_log"
	"maya-service/config"
	"maya-service/constant"
	"maya-service/event"
	modelEvent "maya-service/model/event"
	"maya-service/utils"
)

var OrderNotifyInstance = NewOrderNotify()

type OrderNotify struct {
}

func NewOrderNotify() *OrderNotify {

	return &OrderNotify{}
}

func (o *OrderNotify) Init() {
	event.Subscribe(event.UserEnterNtf, func(ctx context.Context, e event.Event, payload interface{}) {
		data, ok := payload.(*modelEvent.OrderCreateNotify)
		if !ok {
			return
		}

		// 刷新缓存信息
		err := OrderNotifyInstance.SendOrderCreatedNotify(data.OrderId)
		if err != nil {
			log.Error("orderNotify 刷新缓存信息失败")
			return
		}
		return
	})
	return
}

// SendOrderCreatedNotify 发送通知
func (o *OrderNotify) SendOrderCreatedNotify(orderId string) (err error) {
	log.Info("############# 发送抢单通知 SendOrderCreatedNotify", zap.Any("orderNo", orderId))
	// 获取订单详情
	// 获取商品数据
	// 通过企业微信sdk发送通知
	url := constant.TestConfigUrl + "/chat/order"
	if config.Conf.Env == "prod" {
		url = constant.ProdConfigUrl + "/chat/order"
	}

	level := GetSupervisorLevelByOrderNo(orderId)

	content := fmt.Sprintf("莘古人，用户在线急等，<a href=\"%v\"> 点击前往 </a > 速速应单", url)
	userList := GetSuperVisorList([]int{level})
	if len(userList) > 0 {
		fmt.Println(weixin.SendMessageToUsers(userList, content))
	}

	trace_log.DebugLogger(orderId, "########## 发送抢单通知成功 userList：", utils.ToJsonString(userList))

	return
}
